#include "stdlib.h"
#include "stdio.h"
#include "histogram.h"
#include <cstring>

#define MAXLINE 256
/* ---------------------------------------------------------------------- */

Histogram::Histogram()
{
  nitem = 0;
  Key2Hist.clear();
}

/* ---------------------------------------------------------------------- */
 
int Histogram::GetHist(const char *hfile, const int keycol, const int valcol)
{
  nitem = 0;
  FILE *fp = fopen(hfile, "r");
  if (fp){
    // to read the histogram file; if the output format of histogram is changed,
    // this part must be modified accordingly.
    char oneline[MAXLINE], *ptr;
    std::string key;
    double value;

    //fgets(oneline,MAXLINE,fp);
    while (!feof(fp)){
      fgets(oneline,MAXLINE,fp);
      if ( ptr=strchr(oneline,'#') ) *ptr='\0';
      //if ( ptr=strchr(oneline,'*') ) *ptr='\0';
      if ((ptr = strtok(oneline," \t\n\r\f")) == NULL) continue;
      int flag = 0, n = 0;
      do {
        n++;
        if (n == keycol){ key.assign(ptr);   flag |= 1;}
        if (n == valcol){ value = atof(ptr); flag |= 2;}
        if ((flag&3)==3){ Key2Hist[key] = value; break;}
      } while ( ptr = strtok(NULL," \t\n\r\f") );
    }
    fclose(fp);
    nitem = Key2Hist.size();
  }
  if (nitem == 0){
    printf("\nError: file %s not found or empty!\n", hfile);
  }

return nitem;
}

/* ---------------------------------------------------------------------- */
int Histogram::GetValue(std::string key, double &value)
{
  int n = Key2Hist.count(key);
  if (n) value = Key2Hist[key];
  else value = 0.;

return n;
}
/* ---------------------------------------------------------------------- */

Histogram::~Histogram( )
{
  Key2Hist.clear();
}

/* ---------------------------------------------------------------------- */
